<?php

class Captcha {

	public $length;
	public $valid;

	public function __construct ($length = 0) {
		session_start();
		$this->length = $length;
	}

	public function show () {
		$image = new Captcha_Image("", 50 * $this->length, 50);
		$bg = imagecolorallocate($image->handle, 255, 255, 255);
		imagefill($image->handle, 0, 0, $bg);
		$number = "";

		for ($i = 0; $i < $this->length; $i++) {
			$digit = new Captcha_Image("", 25, 25);
			$white = imagecolorallocate($digit->handle, 255, 255, 255);
			$bg = imagecolortransparent($digit->handle, $white);
			imagefill($digit->handle, 0, 0, $bg);
			$red = rand(0, 128);
			$green = rand(0, 128);
			$blue = rand(0, 128);
			$fg = imagecolorallocate($digit->handle, $red, $green, $blue);
			$font = rand(3, 5);
			$char = rand(0, 9);
			$number .= $char;
			imagestring($digit->handle, $font, 0, 0, $char, $fg);
			$angle = rand(0, 50);
			$angle = ($angle % 2 > 0) ? 360 - $angle : $angle;
			$digit->handle = imagerotate($digit->handle, $angle, $bg);
			//if (rand(0, 1) > 0) {
				$width = round($digit->width * 2);
				$height = round($digit->height * 2);
			//} else {
				//$width = $digit->width;
				//$height = $digit->height;
			//}
			$distance = 0;
			if ($i > 0) {
				$distance = rand(0, 5);
				$distance = ($distance % 2 > 0) ? 0 - $distance : $distance;
			}
			imagecopyresized($image->handle, $digit->handle, $i * 50 + $distance, 0, 0, 0, $width, $height, 25, 25);
		}

		$_SESSION['captcha'] = $number;
		$image->output(false);
	}

	public static function check($key) {
		$this->valid = ($_POST['captcha'] == $_SESSION['captcha']);
		return $this->valid;
	}

}

class Captcha_Image {

	public $width;
	public $height;
	public $source;
	public $handle;

	public function __construct ($source="", $width=0, $height=0) {
		if (!empty($source)) {
			$extension = substr($source, -3);
			$extension = ($extension == "jpg") ? "jpeg" : $extension;
			$function = "imagecreatefrom" . $extension;
		}
		$this->handle = empty($source) ? imagecreatetruecolor($width, $height) : $function($source);
		$this->source = empty($source) ? "tempfile_" . time() . ".jpg" : $source;
		$this->width = imagesx($this->handle);
		$this->height = imagesy($this->handle);
	}

	public function output ($save=false) {
		if ($save) {
			imagepng($this->handle, $this->source, 80);
		}
		header("Content-type: image/jpeg");
		imagepng($this->handle);
	}

}

?>